package com.lysj.admin.auth.management.controller;

import cn.hutool.crypto.digest.BCrypt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.lysj.admin.auth.management.AuthConstant;
import com.lysj.admin.auth.management.domain.User;
import com.lysj.admin.auth.management.service.UserService;
import com.lysj.admin.utils.constant.CommonConstant;
import com.lysj.admin.utils.spring.foundation.base.BaseContent;
import com.lysj.admin.utils.web.ParamUtil;
import com.lysj.admin.utils.web.Resp;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Created by zk on 2019-01-02 17:53
 * @description
 */
@RestController
@RequestMapping("/auth")
public class ManagementController extends BaseContent {
    @Resource
    private UserService userService;

    @Value("${secret.key}")
    private String key;
    @Value("${secret.tokenExpiration}")
    private int tokenExpiration;

    @PostMapping("/login")
    public Resp login(String username, String password) {
        User user = userService.findByUsername(username);
        if(ParamUtil.isBlank(user)){
            return new Resp().error(Resp.Status.PARAM_ERROR,"该用户名不存在");
        }
        if(user.getDelFlag().equals(CommonConstant.DEL_FLAG)){
            return new Resp().error(Resp.Status.PARAM_ERROR,"该用户已被禁用");
        }
        if(!BCrypt.checkpw(password,user.getPassword())){
            return new Resp().error(Resp.Status.PARAM_ERROR,"密码错误");
        }
        String token = JWT.create().withIssuer(AuthConstant.AUTH_NAME).withSubject(user.getId())
                .withExpiresAt(new Date(new Date().getTime()+tokenExpiration*60*1000))
                .sign(Algorithm.HMAC512(key));
        return new Resp().success(token,"登录成功");
    }
}
